package com.ruoyi.web.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.base.BaseShop;
import com.ruoyi.system.domain.base.ShopConfigDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IBaseShopService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 工厂配置Controller
 *
 * @author ruoyi
 * @date 2023-02-02
 */
@Api(tags = "工厂配置api")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/base/shopConfig" )
public class BaseShopConfigController extends BaseController {

    private final IBaseShopService iBaseShopService;

//    /**
//     * 查询工厂模型列表
//     */
//    @PreAuthorize("@ss.hasPermi('system:shopConfig:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(BaseShop baseShop)
//    {
//        startPage();
//        LambdaQueryWrapper<BaseShop> lqw = new LambdaQueryWrapper<BaseShop>();
//        if (baseShop.getShopId() != null){
//            lqw.eq(BaseShop::getShopId ,baseShop.getShopId());
//        }
//        if (baseShop.getParentId() != null){
//            lqw.eq(BaseShop::getParentId ,baseShop.getParentId());
//        }
//        if (StringUtils.isNotBlank(baseShop.getAncestors())){
//            lqw.eq(BaseShop::getAncestors ,baseShop.getAncestors());
//        }
//        if (StringUtils.isNotBlank(baseShop.getShopName())){
//            lqw.like(BaseShop::getShopName ,baseShop.getShopName());
//        }
//        if (baseShop.getOrderNum() != null){
//            lqw.eq(BaseShop::getOrderNum ,baseShop.getOrderNum());
//        }
//        if (StringUtils.isNotBlank(baseShop.getShopCode())){
//            lqw.eq(BaseShop::getShopCode ,baseShop.getShopCode());
//        }
//        if (StringUtils.isNotBlank(baseShop.getStatus())){
//            lqw.eq(BaseShop::getStatus ,baseShop.getStatus());
//        }
//        List<BaseShop> list = iBaseShopService.list(lqw);
//        return getDataTable(list);
//    }

    /**
     * 获取工厂配置列表
     */
    @ApiOperation(value = "获取工厂配置列表")
    @GetMapping("/list")
    public AjaxResult list(ShopConfigDTO dto)
    {
        List<ShopConfigDTO> dtos = iBaseShopService.selectShopConfigList(dto);
        return AjaxResult.success(dtos);
    }

    /**
     * 新增工厂
     */
    @Log(title = "工厂配置", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增工厂")
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@Validated @RequestBody BaseShop baseShop)
    {
        if (UserConstants.NOT_UNIQUE.equals(iBaseShopService.checkDeptNameUnique(baseShop)))
        {
            return AjaxResult.error("新增工厂'" + baseShop.getShopName() + "'失败，工厂名称已存在");
        }
        baseShop.setCreateBy(SecurityUtils.getUsername());
        baseShop.setCreateTime(new Date());
        return toAjax(iBaseShopService.insertShop(baseShop));
    }

    /**
     * 查询工厂列表（排除节点）
     */
    @ApiOperation(value = "查询工厂列表（排除节点）")
    @GetMapping("/list/exclude/{shopId}")
    public AjaxResult excludeChild(@PathVariable(value = "shopId", required = false) Long shopId)
    {
        List<BaseShop> depts = iBaseShopService.list();
        Iterator<BaseShop> it = depts.iterator();
        while (it.hasNext())
        {
            BaseShop d = (BaseShop) it.next();
            if (d.getShopId().intValue() == shopId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), shopId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }


    /**
     * 导出工厂模型列表
     */
    @Log(title = "工厂模型" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(BaseShop baseShop) {
        LambdaQueryWrapper<BaseShop> lqw = new LambdaQueryWrapper<BaseShop>(baseShop);
        List<BaseShop> list = iBaseShopService.list(lqw);
        ExcelUtil<BaseShop> util = new ExcelUtil<BaseShop>(BaseShop. class);
        return util.exportExcel(list, "shopConfig" );
    }

    /**
     * 获取工厂模型详细信息
     */
    @ApiOperation(value = "获取工厂模型详细信息")
    @GetMapping(value = "/{shopId}")
    public AjaxResult getInfo(@PathVariable("shopId" ) Long shopId) {
        return AjaxResult.success(iBaseShopService.getById(shopId));
    }

    /**
     * 修改工厂模型
     */
    @ApiOperation(value = "修改工厂模型")
    @Log(title = "工厂模型" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseShop baseShop) {
        baseShop.setCreateBy(SecurityUtils.getUsername());
        baseShop.setCreateTime(new Date());
        return toAjax(iBaseShopService.updateById(baseShop) ? 1 : 0);
    }

    /**
     * 删除工厂模型
     */
    @ApiOperation(value = "删除工厂模型")
    @Log(title = "工厂模型" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{shopIds}" )
    public AjaxResult remove(@PathVariable Long[] shopIds) {
        if (iBaseShopService.hasChildByDeptId(shopIds[0]))
        {
            return AjaxResult.error("存在下级,不允许删除");
        }
        return toAjax(iBaseShopService.removeByIds(Arrays.asList(shopIds)) ? 1 : 0);
    }
}
